import csv
from github import Github

# 创建 GitHub 实例（你可以使用自己的 token）
g = Github("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")

# 读取现有的用户列表
existing_users = set()
try:
    with open('userList.csv', 'r', newline='') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            existing_users.add(row['username'])
except FileNotFoundError:
    print("userList.csv 文件不存在，创建一个新的。")

# 收集新的用户名
new_users = set()  # 存放新用户的集合
max_users_to_collect = 30000

print("start")

for user in g.get_users():
    if user.login not in existing_users:
        new_users.add(user.login)

        # 检查是否收集到足够的新用户
        if len(new_users) >= max_users_to_collect:
            print("Reached 2000 new users, stopping the collection.")
            break

print("start add!!!")
# 将新用户追加到 userList.csv 文件中
if new_users:
    with open('userList.csv', 'a', newline='') as csvfile:
        fieldnames = ['username']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

        # 如果文件是新创建的，写入表头
        if csvfile.tell() == 0:
            writer.writeheader()

        for username in new_users:
            writer.writerow({'username': username})

    print(f"Successfully appended {len(new_users)} new users to userList.csv.")
else:
    print("No new users to append.")
